// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'
import product_data from '../product'; //导入模拟数据
import './style.css'

//使用vue状态管理
Vue.use(Vuex);

//数组重排
function getFilterArray(array) {
  const res = [];
  const json = {};
  for (let i = 0; i < array.length; i++) {
    const element = array[i];
    if (!json[element]) {
      res.push(element);
      json[element] = 1;
    }
  }
  return res;

}
//创建状态管理器
const store = new Vuex.Store({
  state: {
    //商品列表信息
    productList: [],
    //购物车数据
    carList: []

  },
  getters: {
    //品牌
    brands: state => {
      const brands = state.productList.map(item => item.brand);
      return getFilterArray(brands);
    },
    colors: state => {
      const colors = state.productList.map(item => item.color);
      return getFilterArray(colors);
    }


  },
  mutations: {
    //添加商品数据
    setProductList(state, data) {
      state.productList = data;
    },
    //添加商品到购物车
    addCart(state, id) {
      const isAdded = state.carList.find(item => item.id === id);
      if (isAdded) {
        isAdded.count++;
      } else {
        state.carList.push({
          id: id,
          count: 1
        });
      }
    },
    //修改商品数量
    editCartCount(state, payload) {
      const product = state.carList.find(item => item.id === payload.id);
      product.conut += payload.count;
    },
    deleteCart(state, id) {
      const index = state.carList.findIndex(item => item.id === id);
      //删除
      state.carList.splice(index, 1);
    },
    //清空购物车
    emptyCart(state) {
      state.carList = [];
    }



  },
  actions: {
    //请求商品数据
    getProductList(context) {
      setTimeout(() => {
        context.commit('setProductList', product_data);
      }, 500);
    },
    buy(context) {
      return new Promise(resolve => {
        setTimeout(() => {
          context.commit('emptyCart');
          resolve();
        }, 500);
      })
    }
  }

})

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: {
    App
  },
  template: '<App/>'
})
